/**
 * 格式化时间
 * @param date
 * @param fmt
 * @returns
 */

export const formateDate = (date: Date | string | number, fmt: string) => {
  const _this = new Date(date);
  const o: {
    [key: string]: any;
  } = {
    'M+': _this.getMonth() + 1,
    'd+': _this.getDate(),
    'h+': _this.getHours(),
    'm+': _this.getMinutes(),
    's+': _this.getSeconds(),
    'q+': Math.floor((_this.getMonth() + 3) / 3),
    S: _this.getMilliseconds(),
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (_this.getFullYear() + '').substr(4 - RegExp.$1.length),
    );
  for (const k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
      );
  return fmt;
};

/**
 * 获取路由中的参数（自动识别 Hash 模式）
 * @param key 参数名
 * @returns 参数值或 null
 */
export const getRouteQueryParam = (key: string): string | null => {
  // 判断是否为 Hash 模式
  const isHashMode =
    window.location.hash.includes('?') ||
    (window.location.hash && !window.location.search);

  if (isHashMode) {
    const hash = window.location.hash || '';
    const queryIndex = hash.indexOf('?');
    if (queryIndex === -1) return null;
    const queryStr = hash.substring(queryIndex + 1);
    const params = new URLSearchParams(queryStr);
    return params.get(key);
  } else {
    // 常规 URL 参数模式
    const params = new URLSearchParams(window.location.search);
    return params.get(key);
  }
};

export const isAndroidOrIOS = () => {
  const userAgent = navigator.userAgent.toLowerCase();
  if (/android/i.test(userAgent)) {
    return 'Android';
  } else if (/iphone|ipod|ipad/i.test(userAgent)) {
    return 'IOS';
  } else {
    return 'Other';
  }
};
